import axios from 'axios';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import Vue from 'vue';
import router from '../router/index'; // 导入你的路由实例

Vue.use(ElementUI);


// 创建axios实例
const service = axios.create({
  baseURL: 'api',
  timeout: 1000000
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    // 设置请求的Content-Type
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

    // 是否需要设置 token
    // const isToken = (config.headers || {}).isToken === false
    // if (getToken() && !isToken) {
    //   config.headers['Authorization'] = 'Bearer ' + getToken(); // 根据实际情况修改
    // }

    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?';
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName];
        var part = encodeURIComponent(propName) + '=';
        if (value !== null && typeof value !== 'undefined') {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              let params = propName + '[' + key + ']';
              var subPart = encodeURIComponent(params) + '=';
              url += subPart + encodeURIComponent(value[key]) + '&';
            }
          } else {
            url += part + encodeURIComponent(value) + '&';
          }
        }
      }
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    console.log('---响应拦截器---', response);
    // 检查响应是否包含数据以及 code 字段
    if (response.data && response.data.code) {
      const code = response.data.code;
      const msg = response.data.msg;

      if (code === 0 && msg === 'You have to login') {
        // 返回登录页面
        console.log('---/backend/page/login/login.html---', code);
        localStorage.removeItem('userInfo');
        // 使用传递的路由实例进行页面跳转
        router.push({ name: 'login' });
      } else {
        return response.data;
      }
    } else {
      // 处理未包含 code 字段的响应
      // 这里可以添加适当的处理逻辑
      return response;
    }
  },
  (error) => {
    console.log('err' + error);
    let { message } = error;
    if (message === 'Network Error') {
      message = '后端接口连接异常';
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常';
    }
    ElementUI.Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    });

    return Promise.reject(error);
  }
);


export default service;
